﻿using IOA.MES.Client.Clean;
using IOA.MES.Client.Common;
using IOA.MES.Client.EL1;
using IOA.MES.Client.EL2;
using IOA.MES.Client.FinalInspection;
using IOA.MES.Client.Framing;
using IOA.MES.Client.InsulatedResistance;
using IOA.MES.Client.IV;
using IOA.MES.Client.Laminator;
using IOA.MES.Client.Models.Response;
using IOA.MES.Client.NameplatePrinting;
using IOA.MES.Client.NQC;
using IOA.MES.Client.Settings;
using IOA.MES.Client.Sort;
using IOA.MES.Client.Top;
using IOA.MES.Client.Welding;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace IOA.MES.Client
{
    /// <summary>
    /// LoginWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        private bool autoLogin = true;
        private Dictionary<string, string> dictLangs = new Dictionary<string, string>
        {
            { "zh_CN", "简体中文" },
            { "en", "English" },
            { "vn", "Tiếng Việt" },
            { "id", "IndonesiaName" }
        };

        public LoginWindow()
        {
            InitializeComponent();
        }

        public LoginWindow(bool autoLogin)
        {
            this.autoLogin = autoLogin;
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var langFiles = Directory.GetFiles($"{BaseEnv.LocalDirectory}\\res\\lang").OrderByDescending(_ => _).ToList();
            var langs = new List<dynamic>();
            foreach (var langFile in langFiles)
            {
                var fileName = Path.GetFileName(langFile);
                var langName = fileName.Substring(0, fileName.LastIndexOf("."));
                if (dictLangs.ContainsKey(langName))
                {
                    langs.Add(new { Key = langName, Value = dictLangs[langName] });
                }
            }
            cbLangs.ItemsSource = langs;
            if (langs.Any())
            {
                cbLangs.SelectedIndex = 0;
            }

            var autoLoginConfig = BaseEnv.GetStorage("AutoLogin");
            cbAutoLogin.IsChecked = string.IsNullOrWhiteSpace(autoLoginConfig) || string.Equals(autoLoginConfig, "1", StringComparison.CurrentCultureIgnoreCase);

            BaseEnv.ApiRoot = BaseEnv.GetStorage("ApiRoot");
            BaseEnv.WorkshopCode = BaseEnv.GetStorage("WorkshopCode");
            BaseEnv.WeldingOPCHost = BaseEnv.GetStorage("WeldingOPCHost");
            BaseEnv.machineName = BaseEnv.GetStorage("MachineName");
            var machineTypeStr = BaseEnv.GetStorage("MachineType");
            BaseEnv.MachineType = string.IsNullOrWhiteSpace(machineTypeStr) ? -1 : Convert.ToInt32(machineTypeStr);
            var machineId = BaseEnv.GetStorage("MachineId");
            BaseEnv.MachineId = string.IsNullOrWhiteSpace(machineId) ? -1 : Convert.ToInt32(machineId);

            txtUserName.Text = BaseEnv.GetStorage("UserName") ?? string.Empty;
            txtPassword.Password = BaseEnv.GetStorage("UserPassword") ?? string.Empty;

            if (CheckConfig(true))
            {
                var response = BaseEnv.InvokeApi<CheckUpgradeResponse>("/api/Common/CheckUpgrade", new { AppName = BaseEnv.LocalDirectory.Substring(BaseEnv.LocalDirectory.LastIndexOf("\\") + 1), CurrentVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion });
                if (response.ErrCode != 200)
                {
                    CommonMessage.Alert(this, response.ErrMsg);
                    Environment.Exit(0);
                    return;
                }
                else if (response.Data.HasUpgrade)
                {
                    System.Diagnostics.Process.Start($"{BaseEnv.LocalDirectory}\\upgrade\\upgrade.exe");
                    Environment.Exit(0);
                    return;
                }
            }

            var existProcesses = Process.GetProcesses().Where(_ => string.Equals("IOA.MES.Client", _.ProcessName, StringComparison.CurrentCultureIgnoreCase)).ToList();
            foreach (var item in existProcesses)
            {
                if (item.Id != Process.GetCurrentProcess().Id)
                {
                    item.Kill();
                    item.WaitForExit();
                }
            }

            new TaskFactory().StartNew(() =>
            {
                Thread.Sleep(1000);
                Dispatcher.Invoke(new Action(() =>
                {
                    if (cbAutoLogin.IsChecked == true && autoLogin)
                    {
                        btnLogin_Click(null, null);
                    }
                }), DispatcherPriority.Background);
            });
        }

        private bool CheckConfig(bool showConfigWindow = false)
        {
            if (string.IsNullOrWhiteSpace(BaseEnv.ApiRoot) || BaseEnv.MachineType < 0 || string.IsNullOrWhiteSpace(BaseEnv.WorkshopCode))
            {
                if (showConfigWindow)
                {
                    new SettingsIndex().ShowDialog();
                }
                return false;
            }
            var queryMachineTypesResponse = BaseEnv.InvokeApi<QueryMachineTypesResponse>("/api/Common/QueryMachineTypes", new { });
            if (queryMachineTypesResponse.ErrCode != 200)
            {
                CommonMessage.Alert(this, queryMachineTypesResponse.ErrMsg);
                return false;
            }
            else if (!queryMachineTypesResponse.Data.MachineTypes.Any())
            {
                CommonMessage.Alert(this, "获取设备类型列表为空");
                return false;
            }
            else if (!queryMachineTypesResponse.Data.MachineTypes.Any(_ => _.Key == BaseEnv.MachineType))
            {
                CommonMessage.Alert(this, "当前设备类型不合法");
                return false;
            }

            var getWorkshopResponse = BaseEnv.InvokeApi<GetWorkshopResponse>("/api/Common/GetWorkshop", new { WorkshopCode = BaseEnv.WorkshopCode });
            if (getWorkshopResponse.ErrCode != 200)
            {
                CommonMessage.Alert(this, getWorkshopResponse.ErrMsg);
                Environment.Exit(0);
                return false;
            }
            else if (getWorkshopResponse.Data.Workshop == null)
            {
                CommonMessage.Alert(this, "车间不合法，请重新设置");
                return false;
            }
            else if (getWorkshopResponse.Data.Workshop.Status >= 3)
            {
                CommonMessage.Alert(this, "车间状态异常，请重新设置");
                return false;
            }

            return true;
        }

        private bool logining = false;
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckConfig())
            {
                var result = new SettingsIndex().ShowDialog();
                return;
            }
            if (logining)
            {
                return;
            }
            var userName = txtUserName.Text.Trim();
            var password = txtPassword.Password.Trim();
            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                return;
            }

            logining = true;
            btnLogin.Content = "登录中...";
            new TaskFactory().StartNew(() =>
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    var response = BaseEnv.InvokeApi<LoginResponse>("/api/Auth/Login", new
                    {
                        UserName = userName,
                        Password = password,
                        WorkshopCode = BaseEnv.WorkshopCode,
                        MachineType = BaseEnv.MachineType
                    });
                    if (response.ErrCode != 200)
                    {
                        btnLogin.Content = "登  陆";
                        CommonMessage.Alert(this, response.ErrMsg);
                        logining = false;
                        return;
                    }

                    if (cbAutoLogin.IsChecked == true)
                    {
                        BaseEnv.SetStorage("UserName", userName);
                        BaseEnv.SetStorage("UserPassword", password);
                        BaseEnv.SetStorage("AutoLogin", "1");
                    }
                    else
                    {
                        BaseEnv.SetStorage("UserName", "");
                        BaseEnv.SetStorage("UserPassword", "");
                        BaseEnv.SetStorage("AutoLogin", "0");
                    }

                    BaseEnv.UserInfo = response.Data;
                    switch ((MachineType)BaseEnv.MachineType)
                    {
                        case MachineType.WeldingMachine:
                            new WeldingIndex().Show();
                            break;
                        case MachineType.Laminator:
                            new LaminatorIndex().Show();
                            break;
                        case MachineType.LaminatorRework:
                            new LaminatorRework.LaminatorReworkIndex().Show();
                            break;
                        case MachineType.EL1:
                            new EL1Index().Show();
                            break;
                        case MachineType.TopMachine:
                            new TopIndex().Show();
                            break;
                        case MachineType.ELMID:
                            new ELMid.ELMidIndex().Show();
                            break;
                        case MachineType.NQC:
                            new NQCIndex().Show();
                            break;
                        case MachineType.Framing:
                            new FramingIndex().Show();
                            break;
                        case MachineType.Clean:
                            new CleanIndex().Show();
                            break;
                        case MachineType.IV:
                            new IVIndex().Show();
                            break;
                        case MachineType.WithstandVoltage:
                            new InsulatedResistanceIndex().Show();
                            break;
                        case MachineType.EL2:
                            new EL2Index().Show();
                            break;
                        case MachineType.NameplatePrinting:
                            new NameplatePrintingIndex().Show();
                            break;
                        case MachineType.FinalInspection:
                            new FinalInspectionIndex().Show();
                            break;
                        case MachineType.Sort:
                            new SortIndex().Show();
                            break;
                        default:
                            CommonMessage.Alert(this, "请重新设置设备类型\r\nPlease reset the device type");
                            break;
                    }
                    this.Hide();
                }));
            });
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void txtTextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key != System.Windows.Input.Key.Enter)
            {
                return;
            }
            if (!string.IsNullOrWhiteSpace(txtUserName.Text.Trim())
                && !string.IsNullOrWhiteSpace(txtPassword.Password.Trim()))
            {
                btnLogin_Click(null, null);
            }
        }

        private void cbLangs_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var langRd = Application.LoadComponent(new Uri(@"res\lang\" + Convert.ToString(((dynamic)cbLangs.SelectedItem).Key) + ".xaml", UriKind.Relative)) as ResourceDictionary;
            if (langRd != null)
            {
                Application.Current.Resources.MergedDictionaries.Clear();
                Application.Current.Resources.MergedDictionaries.Add(langRd);
            }
        }

        private void Image_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            new SettingsIndex().ShowDialog();
        }
    }
}
